﻿using DataLayer.Entities;
using DataLayer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataLayer
{
    public class CurrencyData
    {
        private IDatabaseEntities _entities;
 
        public CurrencyData() : this(new DatabaseEntities())
        {
        }

        public CurrencyData(IDatabaseEntities entities)
        {
            _entities = entities;
        }

        public decimal? GetCurrentExchangeRate(string fromCountry, string toCountry)
        {
            var fromExchangeRate = (from exchangeRate in _entities.ExchangeRates
                                   where exchangeRate.CountryCode == fromCountry
                                   where exchangeRate.ExchangeDate == DateTime.Today
                                   select exchangeRate).SingleOrDefault();

            var toExchangeRate = (from exchangeRate in _entities.ExchangeRates
                                   where exchangeRate.CountryCode == toCountry
                                   where exchangeRate.ExchangeDate == DateTime.Today
                                  select exchangeRate).SingleOrDefault();

            if (fromExchangeRate == null || toExchangeRate == null) return null;
            return toExchangeRate.Rate / fromExchangeRate.Rate;
        }

        public void SaveExchangeRate(ExchangeRateModel exchangeRate)
        {
            if (!exchangeRate.Id.HasValue)
            {
                _entities.ExchangeRates.Add(new ExchangeRate
                {
                    ExchangeDate = exchangeRate.ExchangeDate,
                    CountryCode = exchangeRate.CountryCode,
                    Rate = exchangeRate.Rate
                });
                _entities.SaveChanges();
            }
            else
            {
                var entity = _entities.ExchangeRates.Where(x => x.Id == exchangeRate.Id.Value).Single();
                entity.ExchangeDate = exchangeRate.ExchangeDate;
                entity.CountryCode = exchangeRate.CountryCode;
                entity.Rate = exchangeRate.Rate;
                _entities.SaveChanges();
            }
        }

        public void DeleteExchangeRate(int id)
        {
            var entity = _entities.ExchangeRates.Where(x => x.Id == id).Single();
            _entities.ExchangeRates.Remove(entity);
            _entities.SaveChanges();
        }
    }
}
